package com.ytjj.qmyx.mall.service.impl;

import com.google.protobuf.Api;
import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.constants.SysConfigConstants;
import com.ytjj.common.dto.mqdto.OrderRecordDto;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.CopyWriterConfigUtil;
import com.ytjj.common.utils.OrderUtils;
import com.ytjj.common.utils.SysConfigUtil;
import com.ytjj.qmyx.mall.constants.IsSalePriceConstant;
import com.ytjj.qmyx.mall.constants.PayModeConstant;
import com.ytjj.qmyx.mall.constants.RedisConstants;
import com.ytjj.qmyx.mall.enums.ActivityTypeEnums;
import com.ytjj.qmyx.mall.mapper.OrdersSpecMapper;
import com.ytjj.qmyx.mall.mapper.GroupBuyUserRelMapper;
import com.ytjj.qmyx.mall.mapper.ProductActivityMapper;
import com.ytjj.qmyx.mall.mapper.ProductMapper;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.request.CreateOrderRequest;
import com.ytjj.qmyx.mall.model.response.AuctionResponse;
import com.ytjj.qmyx.mall.model.response.ProductActivitySpecResponse;
import com.ytjj.qmyx.mall.service.*;
import com.ytjj.qmyx.users.mapper.UsersInfoMapper;
import com.ytjj.qmyx.users.model.UsersInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 活动创建订单的方式
 *
 *
 * @version 1.0
 *
 */
@Service("ACTIVITY")
@Slf4j
public class OrdersActivityServiceImpl implements CreateOrderService<CreateOrderRequest> {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private OrdersService ordersService;

    @Resource
    private SysConfigUtil sysConfigUtil;

    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private ProductActivityMapper productActivityMapper;
    @Autowired
    private YxProductGroupBuyInfoService yxProductGroupBuyInfoService;
    @Autowired
    private YxGroupBuyInfoService yxGroupBuyInfoService;
    @Autowired
    private YxGroupBuyUserRelService yxGroupBuyUserRelService;
    @Resource
    private GroupBuyUserRelMapper groupBuyUserRelMapper;

    @Resource
    private OrdersSpecMapper ordersSpecMapper;

    @Override
    @Transactional
    public Integer createOrder(CreateOrderRequest request) {
        if (null != request.getGroupBuyType()) {
            log.info("===createOrder===进入拼团了");
            //todo 这里是否需要加全局锁来控制并发
            ProductGroupBuyInfo productGroupBuyInfo = yxProductGroupBuyInfoService.queryByProductId(request.getProductId());
            if (null == productGroupBuyInfo) {
                throw new ApiException("拼团活动已结束");
            }
            if (2 == request.getGroupBuyType() && null == request.getGroupBuyId()) {
                throw new ApiException("拼团时参数错误");
            }
            //如果是参团，需要校验参团名额是否还有
            checkGroupBuySurplusPerson(request.getGroupBuyId(), request.getUserId());

        }
        // 活动创建订单
        Product activityProductInfo = productMapper.selectByPrimaryKey(request.getProductId());
        if(null == activityProductInfo) new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.COMMODITY_NOT_EXIST));

        if (Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.IS_STOCE_VERIFY)) > 0 && activityProductInfo.getStock() <= 0) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.INSUFFICIENT_STOCK));
        }
        ProductActivitySpecResponse activitySpec = activityService.getActivityProductSpecById(request.getProductSpecId());
        if (Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.IS_STOCE_VERIFY)) > 0 && activitySpec.getStock() <= 0) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.INSUFFICIENT_STOCK));
        }

        ProductActivity productActivity = new ProductActivity();
        if (null != activitySpec && null != activitySpec.getActivityId()) {
            productActivity = productActivityMapper.selectByPrimaryKey(activitySpec.getActivityId());
        }
        BigDecimal price = activitySpec.getPrice();
        //如果是拼团活动
        if (ActivityTypeEnums.GROUP_WORK.name().equals(activityProductInfo.getActivityType())) {
            ProductGroupBuyInfo productGroupBuyInfo = yxProductGroupBuyInfoService.queryByProductId(activityProductInfo.getId());
            price = productGroupBuyInfo.getGroupPrice();
        }

        Integer isDirectBuy = 0;
        // 支付方式为 “直接购买” 则取出现价字段
        if(PayModeConstant.ORIGINAL_PRICE.equals(request.getFlag())){
            price = activitySpec.getCurPrice();
            isDirectBuy = 1;
//            if (ActivityTypeEnums.GROUP_WORK.name().equals(activityProductInfo.getActivityType())) {
//                ProductGroupBuyInfo productGroupBuyInfo = yxProductGroupBuyInfoService.queryByProductId(activityProductInfo.getId());
//                price = productGroupBuyInfo.getDirectPrice();
//            }
        }
        BigDecimal realTotalMoney = price;
        String orderParentNo = OrderUtils.getOrderCode(request.getUserId());//组合订单号
        //乘商品数量
        BigDecimal originalPrice_new = activityProductInfo.getOriginalPrice();
        BigDecimal price_new = price;
        if (null != request.getProductSum() && request.getProductSum() > 1){
            originalPrice_new = activityProductInfo.getOriginalPrice().multiply(BigDecimal.valueOf(request.getProductSum()));
            price_new = price.multiply(BigDecimal.valueOf(request.getProductSum()));
        }
        // 主订单
        Orders orders = ordersService.saveOrders(request.getUserId(), request.getTel(), originalPrice_new, price_new, request.getOrderSource(),request.getChannel(),null,request.getDynamicId(),orderParentNo,null);
        // 明细订单
        OrdersInfo ordersInfo = ordersService.saveOrdersInfo(orders.getId(), activityProductInfo.getId(), activityProductInfo.getProductName(), activityProductInfo.getProductImg(),
                price, activityProductInfo.getOriginalPrice(), activityProductInfo.getWarehouse(), activityProductInfo.getWarehouseName(),
                activityProductInfo.getWarehouseRule(), request.getSpecialId(), activitySpec.getSkuSpec(), activityProductInfo.getBankerId(), activitySpec.getId(),
                request.getActivityType(), activityProductInfo.getId(), activityProductInfo.getActivityMax(), activityProductInfo.getActivityMin(),
                activityProductInfo.getDescr(),isDirectBuy,request.getPageSourceV2(),null ,2,0, productActivity.getCost(),request.getProductSum(),"");

        try {
            //创建订单的时候应该记录到拼团成员表yx_group_buy_user_rel
            log.info("====create order if create yx_group_buy_user_rel==={}", request.getGroupBuyType());
            if (null != request.getGroupBuyType()) {
                //记录团成员
                boolean result = saveGroupBuyUserRelInfo(request, orders.getUserId(), orders.getOrderNo());
                log.info("===create order save yx_group_buy_user_rel result==={}", result);
            }
            //todo 记录订单规格信息
            ProductSpec productSpec = ordersSpecMapper.selectOrderSpec(request.getProductSpecId());
            ordersSpecMapper.insertOrderSpec(productSpec.getSkuSpec(),orders.getId(),productSpec.getPrice(),productSpec.getOriginalPrice(),productSpec.getCostPrice());
        }catch (Exception e){
            log.error("发送到rabbitmq错误",e);
        }
        return orders.getId();
    }

    @Override
    public Integer cartCreateOrder(CreateOrderRequest request) {
        return null;
    }

    private boolean saveGroupBuyUserRelInfo(CreateOrderRequest request, Integer userId, String orderNo) {
        boolean result = false;
        if (null != request.getGroupBuyType()) {
            //记录团成员
            GroupBuyUserRel groupBuyUserRel = new GroupBuyUserRel();
            groupBuyUserRel.setGroupId(request.getGroupBuyId());//因为这时候还没有成团，所以是null，到时候支付成功后需要创建开团信息，并且回写这个字段
            groupBuyUserRel.setUserId(userId);
            groupBuyUserRel.setGroupRole(request.getGroupBuyType().byteValue());
            groupBuyUserRel.setVirtualUser((byte)0);
            groupBuyUserRel.setCreateTime(new Date());
            groupBuyUserRel.setWinFlag(0);
            groupBuyUserRel.setStatus(0);
            groupBuyUserRel.setOrderNo(orderNo);
            groupBuyUserRel.setHeadImg(request.getHeadImg());
            groupBuyUserRel.setUserName(request.getNickName());
            result = yxGroupBuyUserRelService.insert(groupBuyUserRel);
        }
        log.info("===create order save yx_group_buy_user_rel result==={}", result);
        return result;
    }

    /**
     * 校验团剩余名额是否充足
     * @param groupBuyId
     * @return
     */
    private boolean checkGroupBuySurplusPerson(Integer groupBuyId, Integer userId) {
        log.info("===groupId==={}", groupBuyId);
        if (null == groupBuyId) {//表示非参团，而是开团
            return true;
        }
        GroupBuyInfo groupBuyInfo = yxGroupBuyInfoService.selectById(groupBuyId);//开团表
        if (null == groupBuyInfo) {
            throw new ApiException("找不到拼团信息");
        }
        if (groupBuyInfo.getFinalResult().equals(1)) {
            throw new ApiException("团已满，请重新开团或参团");
        }
        GroupBuyUserRelExample example = new GroupBuyUserRelExample();
        example.createCriteria().andGroupIdEqualTo(groupBuyId).andUserIdEqualTo(userId);
        List<GroupBuyUserRel> haveSelfOrder = groupBuyUserRelMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(haveSelfOrder)) {
            throw new ApiException("您已加入该团，不能重复参团");
        }
        ProductGroupBuyInfo productGroupBuyInfo = yxProductGroupBuyInfoService.queryByProductId(groupBuyInfo.getProductId());//团配置表
        if (null == productGroupBuyInfo || productGroupBuyInfo.getStatus() != 1) {
            throw new ApiException("商品拼团已下架，请重新选择商品");
        }
        GroupBuyUserRelExample groupBuyUserRelExample = new GroupBuyUserRelExample();
        groupBuyUserRelExample.createCriteria().andGroupIdEqualTo(groupBuyId);//.andStatusEqualTo(1).andVirtualUserEqualTo((byte)0)
        List<GroupBuyUserRel> buyPersonNum = groupBuyUserRelMapper.selectByExample(groupBuyUserRelExample);
        if (buyPersonNum.size() >= productGroupBuyInfo.getMinPerson()) {
            throw new ApiException("团已满，请重新开团或参团");
        }
        return true;
    }

//    /**
//     * 活动类型：WALLET_DEDUCTION 抵扣活动商品
//     * 获取当前用户可抵扣金额
//     */
//    private BigDecimal getDeductionMoney(Integer userId,BigDecimal price) {
//        BigDecimal money = usersClient.getMoney(userId);
//        if(money == null || money.doubleValue() <= 0D) return BigDecimal.ZERO;
//        if(money.compareTo(price) > -1){
//            return price;
//        }
//        return money;
//    }
}
